<?php

/**
 * BaseModel
 */
class paomeBaseModel
{
    public $paomeDb;
    public $redis;
    public $table;

    public function __construct(& $base)
    {        
        $this->base = $base;

        $this->redis = &$this->base->redis;
        $this->paomeDb = &$this->base->db;
    }

    public function getRow($where = NULL, $order = NULL)
    {
        return $this->paomeDb->getRowTable($this->table, [], $where, $order);
    }

    public function getOne($col, $where = NULL)
    {
        $where && $where = "where {$where}";

        return $this->paomeDb->getOne("select {$col} from {$this->table} {$where}");
    }

    public function getAll($where = NULL, $order = NULL, $limit = NULL)
    {
        $where && $where = "where {$where}";
        $order && $order = "order by {$order}";
        $limit && $limit = "limit {$limit}";

        return $this->paomeDb->getAll("select * from {$this->table} {$where} {$order} {$limit}");
    }

    public function getList($page = 1, $num = 10, $where = NULL, $order = NULL)
    {
        intval($page) < 1 && $page = 1;
        $result = ['count' => 0, 'pages' => 0, 'page' => $page, 'data' => []];

        $result['count'] = $this->getOne('count(1)', $where);

        if($result['count'] > 0)
        {
            $result['pages'] = ceil($result['count'] / $num);
            $begin = ($page - 1) * $num;
            $limit = "{$begin},{$num}";
            $result['data'] = $this->getAll($where, $order, $limit);
        }

        return $result;
    }

    public function insert(Array $data, $type = 0)
    {
        return $this->paomeDb->insertRow($this->table, $data, $type);
    }

    public function update(Array $data, Array $whereArray = [])
    {
        if($whereArray)
        {
            foreach($whereArray as $wak => $wav)
            {
                $data[$wak] = $wav;
            }
        }

        return $this->paomeDb->updateRowTable($this->table, $data);
    }

    public function delete($where = NULL)
    {
        return $this->paomeDb->delDataTable($this->table, $where);
    }
}